﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DoubanApi.Models;
using ZYStudios.Models;
using ZYStudios.Filter;
using System.Net;
using Newtonsoft.Json;
using System.Web.Security;
using ZYStudios.Common;
using ZYStudios.Helper;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ZYStudios.Controllers
{
    [DataForMasterPageFilter]
    [UserAuthFilter]
    public class DefaultController : BaseController
    {

        private static object aLockObj = new object();

        //
        // GET: /Default/
        [OutputCache(Duration = int.MaxValue, VaryByParam = "*")]
        public ActionResult Index()
        {
            var aMovieCachaProvider = CreateFileCache();
            DoubanApi.DoubanApiClient apiclient = CreateDoubanApi();
            List<MovieModel> aNewMovieList = new List<MovieModel>();


            ZYStudios.Models.Data aData = new Models.Data();


            ZYStudios.Models.DataTableAdapters.IndexImageTableAdapter aIndexImageAdapter = new Models.DataTableAdapters.IndexImageTableAdapter();
            aIndexImageAdapter.Fill(aData.IndexImage);

            List<IndexImageEditModel> IndexImageList = new List<IndexImageEditModel>();
            foreach (var row in aData.IndexImage.ToArray())
            {
                IndexImageList.Add(new IndexImageEditModel()
                {
                    ID = row.ID,
                    ImageUrl = row.ImageUrl,
                    ImageLink = row.ImageLink
                });
            }
            ViewData["IndexImages"] = IndexImageList;


            ZYStudios.Models.DataTableAdapters.ActivityTableAdapter aActivityAdapter = new Models.DataTableAdapters.ActivityTableAdapter();
            aActivityAdapter.Fill(aData.Activity);

            List<ActivityEditModel> ActivityList = new List<ActivityEditModel>();

            foreach (var row in aData.Activity.ToArray())
            {
                ActivityList.Add(new ActivityEditModel()
                {
                    ID = row.ID,
                    ActivityContent = row.ActivityContent,
                    ActivityName = row.ActivityName
                });
            }

            ViewData["Activitys"] = ActivityList.Reverse<ActivityEditModel>().Take(3).ToList();


            ViewData["PlayTimes"] = new List<PlaytimeItemModel>();
            List<PlaytimeModel> aPlayTimeData = PlaytimeHelper.ReadPlayTimeData();

            foreach (var playtime in aPlayTimeData)
            {
                DateTime playdate = new Chinese2Number().ConvertTime(playtime.PlayData);
                if (playdate.Year == DateTime.Now.Year && playdate.Month == DateTime.Now.Month && playdate.Day == DateTime.Now.Day)
                {
                    ViewData["PlayTimes"] = playtime.Movies.Take(3).ToList();
                    break;
                }
            }


            return View("~/Views/Default.aspx");
        }


        public ActionResult About()
        {
            return View();
        }

        public ActionResult QQLoginRedirect()
        {
            return View();
        }

        public void QQLoginAuth(string openId, string accesToken)
        {
            string get_user_info_Url = "https://graph.qq.com/user/get_user_info?access_token=A73B0EAED1F80A86D6B8D9BD13FF5AF6&oauth_consumer_key=222222&openid=166A295F1E0E58A49817B081C35C0E4F";

            WebClient aWebClient = new WebClient();
            aWebClient.Encoding = System.Text.Encoding.UTF8;
            string aResult = aWebClient.DownloadString(get_user_info_Url);

            QQ_User_Info aUser_Info = JsonConvert.DeserializeObject<QQ_User_Info>(aResult);
            Session["User_Info"] = aUser_Info;
            FormsAuthentication.SetAuthCookie(aUser_Info.nickname, false);
        }

        public void LoginOut()
        {
            Session["User_Info"] = null;
            FormsAuthentication.SignOut();
        }

        public ActionResult UserPanel()
        {
            if (Session["User_Info"] != null)
            {
                QQ_User_Info aUser_Info=Session["User_Info"] as QQ_User_Info;
                ViewData["User_Head"] = aUser_Info.figureurl;
                ViewData["User_Name"] = aUser_Info.nickname;
            }
            return View();
        }

        public ActionResult WeiboQPanel()
        {
            return View();
        }

        public void RecordAccessCount()
        {
            if (HttpContext.Application["TodayAccessCount"] == null)
            {
                HttpContext.Application["Today"] = DateTime.Now.ToShortDateString();
                HttpContext.Application["TodayAccessCount"] = 0;
            }

            if (HttpContext.Application["Today"].ToString() != DateTime.Now.ToShortDateString())
            {
                HttpContext.Application["TodayAccessCount"] = 0;
            }

            if (Session["IsFirstAccess"] == null)
            {
                Session["IsFirstAccess"] = false;
                lock (aLockObj)
                {
                    HttpContext.Application["TodayAccessCount"] = (int)HttpContext.Application["TodayAccessCount"] + 1;

                    if (!System.IO.File.Exists(HttpContext.Server.MapPath("/TotalAccess.txt")))
                    {
                        System.IO.File.WriteAllText(HttpContext.Server.MapPath("/TotalAccess.txt"), "0");
                    }
                    string aStrCount = System.IO.File.ReadAllText(HttpContext.Server.MapPath("/TotalAccess.txt"));
                    System.IO.File.WriteAllText(HttpContext.Server.MapPath("/TotalAccess.txt"), (int.Parse(aStrCount) + 1).ToString());
                }
            }
        }

        public ActionResult NotFound()
        {
            return View();
        }
    }
}
